import {getCurrentWindow} from '@tauri-apps/api/window';

class WindowFocusManager {
    constructor() {
        this.window = getCurrentWindow();
        this.isFocused = true;
        this.init();
    }

    async init() {
        try {
            // 检测初始焦点状态
            this.isFocused = await this.window.isFocused();

            // 监听窗口焦点事件
            this.unlisten = await this.window.onFocusChanged(({payload: focused}) => {
                this.isFocused = focused;
                this.handleFocusChange(focused);
            });
        } catch (error) {
            console.error('Window focus manager error:', error);
        }
    }

    handleFocusChange(focused) {
        const event = new CustomEvent('windowFocusChange', {
            detail: { focused }
        });
        window.dispatchEvent(event);

        this.applyFocusStyles(focused);
    }

    applyFocusStyles(focused) {
        const root = document.documentElement;

        if (focused) {
            root.classList.remove('window-blurred');
            root.classList.add('window-focused');
        } else {
            root.classList.remove('window-focused');
            root.classList.add('window-blurred');
        }
    }

    destroy() {
        if (this.unlisten) {
            this.unlisten();
        }
    }
}

export default WindowFocusManager